package com.friendsoft.crm.bean;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;

import com.friendsoft.crm.entity.Contact;
import com.friendsoft.crm.enumeration.State;
import com.friendsoft.crm.exception.NoEntityFoundException;

/**
 * 
 * @author huyduong
 */

@Stateless
public class ContactBean extends BaseEntityBean<Contact> {
	@EJB
	private AddressBean addressBean ;
	
	/**
	 * @param addressBean the addressBean to set
	 */
	public void setAddressBean(AddressBean addressBean) {
		this.addressBean = addressBean;
	}

	/**
	 * find contact using contact's id
	 * @param contact's id
	 * @return contact in database
	 * @throws NoEntityFoundException
	 */
	public Contact getContactById(long id) throws NoEntityFoundException {
		Contact contact = find(id) ;
		if(contact == null) {
			throw new NoEntityFoundException("cannot find contact with id " + id) ;
		}
		return contact ;
	}
	
	/**
	 * create a contact then return a full contact with relation
	 * @param contact
	 * @return persisted contact
	 */
	public Contact createContact(Contact contact) {
		persist(contact) ;
		if(CollectionUtils.isNotEmpty(contact.getAddresses())) {
			addressBean.createAddressesForContact(contact , contact.getAddresses()) ;
		}
		return find(contact.getId()) ;
	}
	
	/**
	 * update contact then return the updated contact with relation
	 * @param contact
	 * @return updated contact
	 * @throws NoEntityFoundException
	 */
	public Contact updateContact(Contact contact) throws NoEntityFoundException {
		if(find(contact.getId()) == null) {
			throw new NoEntityFoundException("cannot find contact with id " + contact.getId()) ;
		}
		merge(contact) ;
		return find(contact.getId()) ;
	}
	
	/**
	 * delete a contact , if this contact is main contact then it is not possible to delete
	 * just mark the state as DELETE and update to the database
	 * @param id
	 * @return the updated contact , maybe a deleted contact 
	 * @throws NoEntityFoundException
	 */
	public Contact deleteContact(long id) throws NoEntityFoundException {
		Contact contact = find(id) ;
		if(contact == null) {
			throw new NoEntityFoundException("cannot find contact with id " + id) ;
		}
		
		if(BooleanUtils.isTrue(contact.isMainContact())) {
			contact.setState(State.DELETED);
			merge(contact) ;
			return contact ;
		}
		
		remove(contact) ;
		return contact ;
	}
}
